<template>
  <form class="page page-localwifi-password">
    <h4 class="text-center">本地WIFI密码查看器</h4>
    <fieldset class="page-body">
      <legend>数据列表</legend>
      <div class="fieldset-inner">
        <div class="table-wrapper">
          <div class="table-header" :style="thStyles">
            <table>
              <tbody>
                <tr>
                  <th v-for="(v,i) in tableHeaders" :key="`th_${i}`" :style="{width: v.width}">{{v.label}}</th>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="table-body">
            <table ref="table">
              <tbody>
                <tr v-for="(v,i) in wifiList" :key="`tr_${i}`"
                  :class="{active: wifiActiveIndex === i}"
                  @click="wifiItemClick(v,i)"
                >
                  <template v-for="(item,index) in tableHeaders">
                    <td :style="{width: item.width}" :key="`td_${i}_${index}`">
                      <button v-if="item.value === 'action'" type="button" class="btn btn-link" @click.stop="delWifiInfo(i)"
                        title="删除">
                        <i class="fa fa-close"></i>
                      </button>
                      <span v-else>{{v[item.value] || ''}}</span>
                    </td>
                  </template>
                </tr>
                <tr v-if="wifiList.length===0" class="nodata-tr"><td>暂无数据</td></tr>
              </tbody>
            </table>
          </div>
        </div>
        <div :class="['qrcode-wrapper', {hidden: (wifiList.length > 0 && wifiActiveIndex === -1)}]">
          <div class="qrcode-header">二维码</div>
          <div class="qrcode-body">
            <div class="row-flex" align="center">
              <div class="row-flex-prefix">Wifi名称</div>
              <div class="row-flex-main"><input class="form-control" type="text" v-model.trim="wifiName" /></div>
            </div>
            <div class="row-flex" align="center">
              <div class="row-flex-prefix">Wifi密码</div>
              <div class="row-flex-main"><input class="form-control" type="text" v-model="wifiPassword" /></div>
            </div>
            <canvas ref="canvas"></canvas>
          </div>
        </div>
      </div>
    </fieldset>
    <div class="page-footer">
      <x-button type="primary" block @click="getWifiNameList">重新获取</x-button>
    </div>
  </form>
</template>

<script>
const iconv = require('iconv-lite')
const {exec} = global.require('child_process')
const os = global.require('os')
let {debounce}  = global.$jstools || {}
let QRCode = global.QRCode || null

export default {
  name: 'localwifi-password',
  data () {
    return {
      platform: os.platform(),
      wifiList: [],
      wifiActiveIndex: -1,
      wifiName: '',
      wifiPassword: '',
      wifiEncryptType: '',
      tableHeaders: [
        {label: 'Wifi名称', value: 'name', width: '35%'},
        {label: '加密类型', value: 'encryptType', width: '20%'},
        {label: 'Wifi密码', value: 'password', width: '35%'},
        {label: '操作', value: 'action', width: '10%'},
      ],
      thStyles: {},
      loadingCount: 0
    }
  },
  computed: {
    qrText () {
      let name = this.wifiName
      let password = this.wifiPassword
      let encryptType = this.wifiEncryptType || 'NONE'
      return `WIFI:T:${encryptType};S:${name};P:${password};;`
    }
  },
  watch: {
    qrText: {
      handler () {this.createQrcode()},
      immediate: true
    }
  },
  mounted () {
    this.getWifiNameList()
  },
  methods: {
    // 获取所有用户配置文件
    getWifiNameList () {
      let command = ''
      if (this.platform === 'win32') {
        command = `chcp 65001 & netsh wlan show profiles`
      } else {
        this.$toast('抱歉，尚不支持该操作系统！')
        return
      }
      exec(command, {encoding: 'buffer'}, (error, stdout, stderr) => {
        if (error) {
          this.$toast('命令执行失败，请以管理员身份运行程序后重试')
          return
        }
        console.error(`stderr: ${stderr}`)
        let str = iconv.decode(stdout, 'utf8') || ''
        // let lst = str.match(/所有用户配置文件 :(.*)/g)
        let lst = str.match(/All User Profile\s*:(.*)/g)
        let result = []
        lst && lst.forEach(v => {
          // let res = v.match(/所有用户配置文件 :(.*)/)
          let res = v.match(/All User Profile\s*:(.*)/)
          let name = ((res || [])[1] || '').trim()
          name && result.push({name, password: '', encryptType: ''})
        })
        this.wifiList = result
        this.wifiList.forEach((v, i) => {
          console.log(v)
          this.getWifiInfo(i)
        })
      })
    },
    // 获取指定Wifi信息
    getWifiInfo (index) {
      let command = ''
      let wifiName = (this.wifiList[index] || {}).name || ''
      if (!wifiName) return
      if (this.platform === 'win32') {
        command = `chcp 65001 & netsh wlan show profile name="${wifiName}" key=clear`
      // } else if (this.platform === 'linux') {
      //   command = `sudo cat /etc/NetworkManager/system-connections/${wifiName}`
      // } else if (this.platform === 'darwin') {
      //   command = `security find-generic-password -D "AirPort network password" -wa "${wifiName}"`
      } else {
        return
      }
      exec(command, (error, stdout, stderr) => {
        if (error) {
          this.$toast('命令执行失败，请以管理员身份运行程序后重试')
          return
        }
        console.log(`stdout: ${stdout}`)
        console.error(`stderr: ${stderr}`)
        let str = iconv.decode(stdout, 'utf8') || ''
        // console.log(str)
        // let res1 = str.match(/'关键内容 {6}:(.*)/)
        // let res2 = str.match(/'身份验证 {6}:(.*)/)
        let res1 = str.match(/Key Content\s*: (.+)/)
        let res2 = str.match(/Authentication\s*: (.+)/)
        res1 && res1[1] && this.$set(this.wifiList[index], 'password', res1[1])
        res2 && res2[1] && this.$set(this.wifiList[index], 'encryptType', res2[1])
      })
    },
    // 删除指定Wifi信息
    delWifiInfo (index) {
      let command = ''
      let wifiName = (this.wifiList[index] || {}).name || ''
      if (!wifiName) return
      if (this.platform === 'win32') {
        command = `chcp 65001 & netsh wlan delete profile name="${wifiName}"`
      } else {
        return
      }
      exec(command, (error, stdout, stderr) => {
        if (error) {
          this.$toast('命令执行失败，请以管理员身份运行程序后重试')
          return
        }
        this.$toast('命令执行完成')
        // this.getWifiNameList()
        this.wifiList.splice(index, 1)
        console.log(error, stdout, stderr)
      })
    },
    // 单条被点击
    wifiItemClick (item, index) {
      this.wifiActiveIndex = (this.wifiActiveIndex === index ? -1 : index)
      if (this.wifiActiveIndex === -1) {
        this.wifiName = ''
        this.wifiPassword = ''
        this.wifiEncryptType = ''
      } else {
        this.wifiName = item.name
        this.wifiPassword = item.password
        this.wifiEncryptType = item.encryptType
      }
      this.createQrcode()
    },
    // 生成二维码
    createQrcode () {
      if (!this.qrText) return
      if (!this.$refs.canvas) return
      this.$nextTick(() => {
        let width = document.documentElement.clientWidth / 5
        QRCode.toCanvas(this.$refs.canvas, this.qrText, {width}, (err) => {
          if (err) console.error(err)
          console.log('success!')
        })
      })
    },
    // 修正滚动条
    checkScroll: debounce(function () {
      this.$nextTick(() => {
        if (!this.$refs.table) return
        let tableHeight = this.$refs.table.clientHeight
        let tableParentHeight = this.$refs.table.parentNode.clientHeight
        if (tableHeight > tableParentHeight) {
          this.thStyles = {overflow: 'hidden scroll'}
        } else {
          this.thStyles = {overflow: 'hidden'}
        }
      })
    })
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.page-localwifi-password {
	display: flex;
	flex-direction: column;
	.page-body {
		height: 0;
		flex-grow: 1;
    .fieldset-inner {
      width: 100%;
      height: calc(100% - 2em);
      display: flex;
      overflow: hidden;
    }
    .table-wrapper {
      width: 0;
      flex-grow: 1;
      transition: all .25s linear;
    }
    .qrcode-wrapper {
      width: 25vw;
      margin-right: 0;
      border: 1px solid @borderGrey;
      background-color: @bgMain;
      transition: all .25s linear;
      &.hidden {
        margin-right: -25vw;
      }
      .qrcode-header {
        height: 2em;
        line-height: 2;
        border-bottom: 1px solid @borderGrey;
        text-align: center;
      }
      .qrcode-body {
        height: calc(100% - 2em);
        padding: 1.5vw 2.5vw;
        overflow: hidden auto;
        text-align: center;
      }
      .row-flex {
        margin-bottom: 1em;
      }
      canvas {
        width: 20vw;
        height: 20vw;
      }
    }
    .table-header,
    .table-body {
      table {
        width: 100%;
        border: 1px solid @borderGrey;
        tr {height: 2em;}
        th, td {
          border: 1px solid @borderGrey;
          text-align: center;
          vertical-align: middle;
        }
        .nodata-tr {
          height: 100%;
          font-size: 16px;
          color: #999;
        }
      }
    }
    .table-body {
      height: calc(100% - 2em);
      overflow: auto;
      table {
        min-height: 100%;
      }
      tr {
        transition: all .2s linear;
        cursor: pointer;
      }
      tr.active {
        background-color: @bgGrey;
      }
    }
  }
  .page-footer {
    margin-top: 1em;
  }
}
</style>
